#include "view.h"
#include "mainwindow.h"
#include <QMouseEvent>
#include <QContextMenuEvent>
#include <QMenu>

View::View(MainWindow* mainWindow):m_mainWindow(mainWindow){
    m_hold = false;
    m_grid = false;
    setAlignment(Qt::AlignLeft | Qt::AlignTop);
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    setContextMenuPolicy(Qt::DefaultContextMenu);
}

void View::mouseMoveEvent(QMouseEvent *event) {
    qreal x = mapToScene(event->pos()).x();
    qreal y = mapToScene(event->pos()).y();
    QString str = QString::number(x);
    str.append(",");
    str.append(QString::number(y));
    m_mainWindow->setBarLabel(str);

    if(m_hold){
        m_mainWindow->mouseDrag(x,y);
    }
}


void View::mousePressEvent(QMouseEvent *event) {
    if (event->button() == Qt::RightButton) {
        return;
    }
    qreal x = mapToScene(event->pos()).x();
    qreal y = mapToScene(event->pos()).y();
    m_hold = true;
    m_mainWindow->mouseClick(x,y);
}

void View::mouseReleaseEvent(QMouseEvent *event) {
    if (event->button() == Qt::RightButton) {
        return;
    }
    qreal x = mapToScene(event->pos()).x();
    qreal y = mapToScene(event->pos()).y();
    m_hold = false;
    m_mainWindow->mouseRelease(x,y);
}

void View::contextMenuEvent(QContextMenuEvent *event) {

    //itemAt(event->pos().x(),event->pos().y(), const QTransform & deviceTransform );
    QMenu *menu = new QMenu;

    QAction *action = new QAction(QString(tr("Show grid")), this);
    menu->addAction(action);
    action->setCheckable(true);
    action->setChecked(m_grid);
    connect(action, SIGNAL(triggered()), this, SLOT(redrawBackground()));


    action = new QAction(QString(tr("End")), this);
    action->setDisabled(true);
    menu->addAction(action);

    action = new QAction(QString(tr("Middle")), this);
    action->setDisabled(true);
    menu->addAction(action);

    action = new QAction(QString(tr("Center")), this);
    action->setDisabled(true);
    menu->addAction(action);

    action = new QAction(QString(tr("Quadrant")), this);
    action->setDisabled(true);
    menu->addAction(action);

    menu->exec(mapToGlobal(event->pos()));

}

void View::redrawBackground(){
    m_grid = !m_grid;
    invalidateScene(QRectF(rect()),QGraphicsScene::BackgroundLayer);
    viewport()->update();
}

void View::drawBackground(QPainter *painter, const QRectF &rect){

    if (!m_grid) {
        return;
    }
    int step = 30;
    painter->setPen(QPen(QColor(200, 200, 255, 125)));

    // draw horizontal grid
    qreal start = rect.top();
    for (qreal y = start - step; y < rect.bottom(); ) {
       y += step;
       painter->drawLine(rect.left(), y, rect.right(), y);
    }

    // now draw vertical grid
    start = rect.left();
    for (qreal x = start - step; x < rect.right(); ) {
       x += step;
       painter->drawLine(x, rect.top(), x, rect.bottom());
    }
}
